package com.itya.weatherback.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itya.weatherback.domain.getWeatherAli.vo.*;
import com.itya.weatherback.domain.getWeatherAli.weatherJson.*;
import com.itya.weatherback.domain.getWeatherAli.vo.HourData;
import com.itya.weatherback.mapper.*;

import com.itya.weatherback.utils.HttpUtils;
import com.itya.weatherback.utils.Result;

import com.itya.weatherback.utils.WindDirectionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


import java.io.UnsupportedEncodingException;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import static com.itya.weatherback.utils.WindDirectionUtils.extractWindLevel;

@RestController
@RequestMapping("/weather")
public class WeatherController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WeatherMapper weatherMapper;

    @Autowired
    private ThreeHourMapper threeHourMapper;

    @Autowired
    private LifeIndexMapper lifeIndexMapper;

    @Autowired
    private DailyForecastMapper dailyForecastMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private Hour1Mapper hour1Mapper;

    @Value("${weather.hefeng.key}")
    private String hefengKey;

    @Value("${weather.hefeng.base-url}")
    private String baseUrl;

    @Value("${weather.aliyun.appcode}")
    private String aliyunAppCode;

    @Autowired
    private CitysMapper citysMapper;


    /**
     * 公共api搜索城市天气
     * @param cityName 城市名称
     * @return 天气数据
     */
    @GetMapping("/searchCityWeather")
    public Result<String> searchAndSyncCityWeather(@RequestParam String cityName) {
        try {
            // 使用公共用户ID（如0）或默认用户
            int publicUserId = 0;

            // 调用阿里云API获取天气数据
            String host = "https://getweather.market.alicloudapi.com";
            String path = "/lundear/weather1d";
            String method = "GET";
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "APPCODE " + aliyunAppCode);
            Map<String, String> querys = new HashMap<>();
            querys.put("areaCn", cityName);
            querys.put("needObserve", "1");
            querys.put("needIndex", "1");

            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            if (response.getStatusLine().getStatusCode() != 200) {
                return Result.error("天气数据获取失败");
            }

            String responseBody = EntityUtils.toString(response.getEntity());
            AliyunWeatherResponse aliyunResponse = JSON.parseObject(responseBody, AliyunWeatherResponse.class);
            DataInfo data = aliyunResponse.getData();

            // 处理NOW数据（复用现有逻辑）
            Now now = data.getNow();

            // 查询是否已有公共城市数据
            LambdaQueryWrapper<CityWeather> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CityWeather::getCityName, cityName)
                    .eq(CityWeather::getUserId, publicUserId);
            CityWeather existing = weatherMapper.selectOne(wrapper);

            CityWeather cityWeather;
            if (existing == null) {
                // 插入新城市（使用公共用户ID）
                cityWeather = new CityWeather();
                cityWeather.setUserId(publicUserId);
                cityWeather.setCityName(getStringValueOrDefault(now.getCityname(), "未知"));
                cityWeather.setWeatherCondition(getStringValueOrDefault(now.getWeather(), "未知"));
                cityWeather.setPrecipitation(getStringValueOrDefault(now.getRain(), "未降雨"));
                cityWeather.setCurrentTemperature(parseInt(now.getTemp()));
                cityWeather.setPerceivedTemperature(parseInt(now.getTemp()) + 2);
                cityWeather.setWindDirection(WindDirectionUtils.getChineseDirection(getStringValueOrDefault(now.getWde(), "未知")));
                cityWeather.setWindSpeedLevel(extractWindLevel(getStringValueOrDefault(now.getWS(), "无风")));

                weatherMapper.insert(cityWeather);
            } else {
                // 更新现有城市数据
                cityWeather = updateExistingWeather(existing, now);
            }

            int cityWeatherId = cityWeather.getId();
            System.out.println("城市ID为：" + cityWeatherId);

            // 处理24小时数据
            JSONObject observe24h = JSON.parseObject(responseBody)
                    .getJSONObject("data")
                    .getJSONObject("observe24h");
            List<HourData> hourDataList = JSON.parseArray(observe24h.getString("od2"), HourData.class);
            handleHourlyData(cityWeatherId, hourDataList);

            // 处理生活指数
            handleLifeIndex(cityWeatherId, data);


            // 调用阿里云API获取天气数据

            path = "/lundear/weather7d";

            // 设置请求头
            headers.put("Authorization", "APPCODE " + aliyunAppCode);
            // 设置查询参数
            querys = new HashMap<>();
            querys.put("areaCn", cityName);
            querys.put("needObserve", "1");//是否需要24小时天气指数；1:需要，0:不需要
            querys.put("needIndex", "1");//是否需要生活指数数据；1:需要，0:不需要

            // 使用 HttpUtils 发起请求
            response = HttpUtils.doGet(host, path, method, headers, querys);

            int statusCode = response.getStatusLine().getStatusCode();
            responseBody = EntityUtils.toString(response.getEntity());;

            // 验证HTTP响应状态
            if (statusCode != 200) {
                return Result.error("天气数据获取失败，HTTP状态码：" + statusCode);
            }

            aliyunResponse = JSON.parseObject(responseBody, AliyunWeatherResponse.class);

            //天气数据
            data = aliyunResponse.getData();
            System.out.println("天气数据：" + data);

            // 处理7天预报
            handleSevenDayForecast(cityWeatherId, data);

            return Result.success("天气数据已同步");
        } catch (Exception e) {
            return Result.error("同步失败: " + e.getMessage());
        }
    }


    /**
     * 公共api获取城市天气
     * @param cityName 城市名
     * @return 天气数据
     */
    @GetMapping("/getCommonWeather")
    public Result<CityWeather> getCommonWeather(@RequestParam String cityName) {
        int publicUserId = 0; // 使用公共用户ID

        LambdaQueryWrapper<CityWeather> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CityWeather::getCityName, cityName)
                .eq(CityWeather::getUserId, publicUserId);
        CityWeather cityWeather = weatherMapper.selectOne(wrapper);

        if (cityWeather == null) {
            return Result.error("城市天气数据不存在");
        }

        // 查询24小时数据
        LambdaQueryWrapper<HourData> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(HourData::getCityWeatherId, cityWeather.getId());
        List<HourData> hourDataList = hour1Mapper.selectList(wrapper1);
        //逆序
        Collections.reverse(hourDataList);
        System.out.println(hourDataList);
        cityWeather.setHourDataList(hourDataList);

        // 查询生活指数
        LambdaQueryWrapper<LifeIndex> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(LifeIndex::getCityWeatherId, cityWeather.getId());
        LifeIndex lifeIndex = lifeIndexMapper.selectOne(wrapper2);
        cityWeather.setLifeIndex(lifeIndex);

        // 查询7天预报（包含当天）
        LambdaQueryWrapper<DailyForecast> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.eq(DailyForecast::getCityWeatherId, cityWeather.getId())
                .ge(DailyForecast::getForecastDate, LocalDate.now())
                .orderByAsc(DailyForecast::getForecastDate); // 按日期升序排列

        List<DailyForecast> dailyForecasts = dailyForecastMapper.selectList(wrapper3);

        // 截取前7天数据（包含当天）
        if (dailyForecasts.size() > 7) {
            dailyForecasts = dailyForecasts.subList(0, 7); // 取前7条
        }

        System.out.println("现在的日期:"+LocalDate.now());
        System.out.println("dailyForecasts: "+dailyForecasts);

        cityWeather.setDailyForecasts(dailyForecasts);


        return Result.success(cityWeather);
    }


    /**
     * 添加城市数据网格显示
     * @return 添加成功
     */
    @GetMapping("/getCityGridList")
    public Result<List<String>> getCityGridList() {

        List<CityGridData> cityGridDataList = citysMapper.selectList(null);
        //提取cityName
        List<String> cityNameList = cityGridDataList.stream().map(CityGridData::getCityName).collect(Collectors.toList());
        return Result.success(cityNameList);
    }


    /**
     * 通过username得到城市列表，并更新每个城市的数据
     * @param username 用户名
     * @return 城市列表
     */
    @GetMapping("/getCityNameListWithUpdate")
    public Result<List<String>> getCityNameListWithUpdate(@RequestParam String username) {
        try {
            // 1. 获取用户ID
            LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.eq(User::getUsername, username);
            User user = userMapper.selectOne(userWrapper);
            if (user == null) {
                return Result.error("用户不存在");
            }
            int userId = Math.toIntExact(user.getId());

            // 2. 查询用户关联城市
            LambdaQueryWrapper<CityWeather> cityWrapper = new LambdaQueryWrapper<>();
            cityWrapper.eq(CityWeather::getUserId, userId);
            List<CityWeather> cityWeatherList = weatherMapper.selectList(cityWrapper);

            // 3. 异步更新所有城市天气数据
            List<String> cityNameList = cityWeatherList.stream()
                    .map(CityWeather::getCityName)
                    .collect(Collectors.toList());

            System.out.println("城市列表：" + cityNameList);

            // 异步更新数据
            updateAllCitiesDataAsync(cityNameList, userId);

            return Result.success(cityNameList);

        } catch (Exception e) {
            return Result.error("获取城市列表失败: " + e.getMessage());
        }
    }


    /**
     * 使用阿里云API同步指定城市的天气数据到数据库
     * 用户添加城市数据
     */
    @GetMapping("/getWeatherFromAliyun")
    public Result<String> syncWeatherDataFromAliyun(
            @RequestParam String cityName,
            @RequestParam String username,
            @RequestParam String addData) {

        try {
            System.out.println("hhhhhhhhhhhhhhhhhhhhhhhhh");
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getUsername, username);
            User user = userMapper.selectOne(userLambdaQueryWrapper);
            System.out.println( user.toString());
            if (user == null)
                return Result.error("用户不存在");
            int userId = Math.toIntExact(user.getId());
            System.out.println("用户id: " + userId);
            System.out.println("用户名称:"+ username);
            System.out.println("城市名称:"+ cityName);
            System.out.println("添加数据:"+ addData);

            //如果城市已添加，返回信息
            LambdaQueryWrapper<CityWeather> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(CityWeather::getUserId,userId);
            wrapper1.eq(CityWeather::getCityName,cityName);
            CityWeather cityWeather1 = weatherMapper.selectOne(wrapper1);
            //System.out.println(cityWeather1.toString());

//            if (cityWeather1 != null && addData.equals("add"))
//                return Result.error("该城市已添加");

//            if (cityWeather1 != null && addData.equals("update"))
//            {
//
//            }
//

            // 构建阿里云天气API请求
            String host = "https://getweather.market.alicloudapi.com";
            String requireDays = "weather1d";
            String path = "/lundear/"+requireDays;
            String method = "GET";
            // 设置请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "APPCODE " + aliyunAppCode);
            // 设置查询参数
            Map<String, String> querys = new HashMap<>();
            querys.put("areaCn", cityName);
            querys.put("needObserve", "1");//是否需要24小时天气指数；1:需要，0:不需要
            querys.put("needIndex", "1");//是否需要生活指数数据；1:需要，0:不需要
            // 使用 HttpUtils 发起请求
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);

            int statusCode = response.getStatusLine().getStatusCode();
            String responseBody = EntityUtils.toString(response.getEntity());
            System.out.println("响应数据：" + responseBody);

            // 验证HTTP响应状态
            if (statusCode != 200) {
                return Result.error("天气数据获取失败，HTTP状态码：" + statusCode);
            }

            AliyunWeatherResponse aliyunWeatherResponse = new AliyunWeatherResponse();
            aliyunWeatherResponse = JSON.parseObject(responseBody, AliyunWeatherResponse.class);

            //天气数据
            DataInfo data = aliyunWeatherResponse.getData();
            System.out.println("天气数据：" + data);


            // 从原始JSON中提取嵌套数组
            JSONObject observe24h = JSON.parseObject(responseBody)
                    .getJSONObject("data")
                    .getJSONObject("observe24h");

            System.out.println("24小时数据JSON：" + observe24h);
            List<HourData> hourDataList = JSON.parseArray(observe24h.getString("od2"), HourData.class);
            System.out.println("24小时数据：" + hourDataList);

            //判断此用户id有没有对应的城市数据
            LambdaQueryWrapper<CityWeather> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CityWeather::getUserId,userId);
            wrapper.eq(CityWeather::getCityName,cityName);
            CityWeather cityWeather = weatherMapper.selectOne(wrapper);
            CityWeather newCityWeather = new CityWeather();


            //处理NOW数据
            Now now = data.getNow();
            //插入新天气数据
            if (cityWeather == null)
            {
                newCityWeather = createNewWeather(userId,now);

            }
            else{
                updateExistingWeather(cityWeather,now);
            }


            //处理24小时数据
            //最终cityWeatherId
            int finalCityWeatherId = cityWeather == null ? newCityWeather.getId() : cityWeather.getId();
            handleHourlyData(finalCityWeatherId, hourDataList);

            //处理生活指数数据
            handleLifeIndex(finalCityWeatherId,data);



            //处理7天预报数据
            requireDays = "weather7d";
            path = "/lundear/"+requireDays;
            method = "GET";
            // 设置请求头
            headers.put("Authorization", "APPCODE " + aliyunAppCode);
            // 设置查询参数
            querys = new HashMap<>();
            querys.put("areaCn", cityName);
            querys.put("needObserve", "1");//是否需要24小时天气指数；1:需要，0:不需要
            querys.put("needIndex", "1");//是否需要生活指数数据；1:需要，0:不需要

            // 使用 HttpUtils 发起请求
            response = HttpUtils.doGet(host, path, method, headers, querys);

            statusCode = response.getStatusLine().getStatusCode();
            responseBody = EntityUtils.toString(response.getEntity());;

            // 验证HTTP响应状态
            if (statusCode != 200) {
                return Result.error("天气数据获取失败，HTTP状态码：" + statusCode);
            }

            aliyunWeatherResponse = JSON.parseObject(responseBody, AliyunWeatherResponse.class);

            //天气数据
            data = aliyunWeatherResponse.getData();
            System.out.println("天气数据：" + data);

            handleSevenDayForecast(finalCityWeatherId,data);



            return Result.success("阿里云天气数据同步成功");

        } catch (UnsupportedEncodingException e) {
            System.out.println("参数编码失败: " + e.getMessage());
            return Result.error("参数编码失败: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("天气数据同步失败: " + e.getMessage());
            return Result.error("天气数据同步失败: " + e.getMessage());
        }
    }

    /**
     * 通过用户名获取简化版天气数据列表
     * @param username 用户名
     * @return 简化天气数据列表
     */
    @GetMapping("/userWeatherDataList")
    public Result<List<SimpleWeatherData>> getSimpleWeatherListByUser(
            @RequestParam String username) {
        try {
            // 1. 获取用户ID
            LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.eq(User::getUsername, username);
            User user = userMapper.selectOne(userWrapper);

            if (user == null) {
                return Result.error("用户不存在");
            }
            Long userId = user.getId();

            // 2. 查询用户所有城市基础信息
            LambdaQueryWrapper<CityWeather> cityWrapper = new LambdaQueryWrapper<>();
            cityWrapper.eq(CityWeather::getUserId, userId);
            List<CityWeather> cityList = weatherMapper.selectList(cityWrapper);

            if (cityList.isEmpty()) {
                return Result.error("用户未关联任何城市");
            }

            // 3. 批量查询7天预报数据
            List<Integer> cityIds = cityList.stream()
                    .map(CityWeather::getId)
                    .collect(Collectors.toList());

            LambdaQueryWrapper<DailyForecast> forecastWrapper = new LambdaQueryWrapper<>();
            forecastWrapper.in(DailyForecast::getCityWeatherId, cityIds)
                    .le(DailyForecast::getForecastDate, LocalDate.now())
                    .orderByAsc(DailyForecast::getForecastDate);
            List<DailyForecast> forecasts = dailyForecastMapper.selectList(forecastWrapper);

            // 4. 数据组装
            List<SimpleWeatherData> result = new ArrayList<>();

            for (CityWeather city : cityList) {
                SimpleWeatherData data = new SimpleWeatherData();
                data.setCityName(city.getCityName());
                data.setCurrentTemperature(city.getCurrentTemperature());
                data.setWeatherCondition(city.getWeatherCondition());

                // 查找当天预报数据
                Optional<DailyForecast> todayForecast = forecasts.stream()
                        .filter(f -> f.getCityWeatherId() == city.getId())
                        .findFirst();


                data.setMinTemperature(todayForecast
                        .map(DailyForecast::getMinTemperature)
                        .orElse(0));

                data.setMaxTemperature(todayForecast
                        .map(DailyForecast::getMaxTemperature)
                        .orElse(0));


                result.add(data);
            }

            return Result.success(result);

        } catch (Exception e) {
            return Result.error("获取天气数据失败: " + e.getMessage());
        }
    }


    /**
     * 用户删除天气数据
     * @param cityName 城市名称
     * @param username 用户名
     * @return 删除结果
     */
    @DeleteMapping("/deleteUserWeatherData")
    public Result<String> deleteUserWeatherData(@RequestParam String cityName,@RequestParam String username){
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        int userId = Math.toIntExact(user.getId());
        LambdaQueryWrapper<CityWeather> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(CityWeather::getUserId, userId)
                .eq(CityWeather::getCityName, cityName);
        CityWeather deleteData = weatherMapper.selectOne(deleteWrapper);
        if (deleteData == null)
            return Result.error("没有该城市数据");

        int weatherId = deleteData.getId();

        int code = weatherMapper.deleteById(deleteData);


        //删除其他数据

        //24小时预报数据
        LambdaQueryWrapper<HourData> hourDataLambdaQueryWrapper = new LambdaQueryWrapper<>();
        hourDataLambdaQueryWrapper.eq(HourData::getCityWeatherId, weatherId);
        List<HourData> list = hour1Mapper.selectList(hourDataLambdaQueryWrapper);
        int code1 = hour1Mapper.deleteByIds(list);
        System.out.println("删除成功24小时数据"+code1);

        //生活指数数据
        LambdaQueryWrapper<LifeIndex> lifeIndexLambdaQueryWrapper = new LambdaQueryWrapper<>();
        lifeIndexLambdaQueryWrapper.eq(LifeIndex::getCityWeatherId, weatherId);
        LifeIndex lifeIndex = lifeIndexMapper.selectOne(lifeIndexLambdaQueryWrapper);
        int code2 = lifeIndexMapper.deleteById(lifeIndex);
        System.out.println("删除生活指数数据：" + code2);

        //7天预报数据
        LambdaQueryWrapper<DailyForecast> dailyForecastLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dailyForecastLambdaQueryWrapper.eq(DailyForecast::getCityWeatherId, weatherId);
        List<DailyForecast> dailyForecasts = dailyForecastMapper.selectList(dailyForecastLambdaQueryWrapper);
        int code3 = dailyForecastMapper.deleteByIds(dailyForecasts);
        System.out.println("删除7天预报数据：" + code3);


        if (code == 1 && code1 >= 1 && code2 == 1 && code3 >= 1) {
            return Result.success(String.format("删除%s天气数据成功", cityName));
        }
        else
            return Result.error(String.format("删除%s天气数据失败", cityName));

    }



    /**
     * 获取用户详情天气信息，管理城市界面点击跳转
     * @param cityName 城市名
     * @param username 用户名
     * @return 天气信息
     */
    @GetMapping("/getUserDetailWeather")
    public Result<CityWeather> getUserDetailWeather(@RequestParam String cityName,@RequestParam String username) {

        //得到userId
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getUsername,username);
        User user = userMapper.selectOne(userWrapper);
        if (user == null)
        {
            return Result.error("用户不存在");
        }
        Long userId = user.getId();

        //得到城市id
        LambdaQueryWrapper<CityWeather> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CityWeather::getCityName,cityName);
        wrapper.eq(CityWeather::getUserId,userId);
        CityWeather cityWeather = weatherMapper.selectOne(wrapper);
        if (cityWeather == null)
        {
            return Result.error("用户拥有城市不存在");
        }


        // 查询24小时数据
        LambdaQueryWrapper<HourData> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(HourData::getCityWeatherId, cityWeather.getId());
        List<HourData> hourDataList = hour1Mapper.selectList(wrapper1);
        //逆序
        Collections.reverse(hourDataList);
        System.out.println(hourDataList);
        cityWeather.setHourDataList(hourDataList);

        // 查询生活指数
        LambdaQueryWrapper<LifeIndex> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(LifeIndex::getCityWeatherId, cityWeather.getId());
        LifeIndex lifeIndex = lifeIndexMapper.selectOne(wrapper2);
        cityWeather.setLifeIndex(lifeIndex);

        // 查询7天预报（包含当天）
        LambdaQueryWrapper<DailyForecast> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.eq(DailyForecast::getCityWeatherId, cityWeather.getId())
                .ge(DailyForecast::getForecastDate, LocalDate.now())
                .orderByAsc(DailyForecast::getForecastDate); // 按日期升序排列

        List<DailyForecast> dailyForecasts = dailyForecastMapper.selectList(wrapper3);

        // 截取前7天数据（包含当天）
        if (dailyForecasts.size() > 7) {
            dailyForecasts = dailyForecasts.subList(0, 7); // 取前7条
        }

        System.out.println("现在的日期:"+LocalDate.now());
        System.out.println("dailyForecasts: "+dailyForecasts);

        cityWeather.setDailyForecasts(dailyForecasts);

        return Result.success(cityWeather);
    }


    /**
     * 处理生活指数（存在则更新，不存在则插入）
     * @param cityWeatherId 城市天气ID
     * @param data 天气数据
     */
    private void handleLifeIndex(int cityWeatherId, DataInfo data) {
        try {
            // 查询是否存在现有生活指数记录
            LambdaQueryWrapper<LifeIndex> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LifeIndex::getCityWeatherId, cityWeatherId);
            LifeIndex existing = lifeIndexMapper.selectOne(wrapper);

            LifeIndex lifeIndex;
            if (existing != null) {
                // 更新现有记录
                lifeIndex = existing;
            } else {
                // 创建新记录
                lifeIndex = new LifeIndex();
                lifeIndex.setCityWeatherId(cityWeatherId);
            }

            // 提取生活指数数据
            if (data.getLifeIndex() != null) {
                // 直接赋值 state 值（假设字段为 String 类型）
                lifeIndex.setColdRiskIndex(data.getLifeIndex().getColdRiskIndex());
                lifeIndex.setUvIndex(data.getLifeIndex().getUvIndex());
                lifeIndex.setSportIndex(data.getLifeIndex().getSportIndex());
                lifeIndex.setCarWashIndex(data.getLifeIndex().getCarWashIndex());
                lifeIndex.setDressIndex(data.getLifeIndex().getDressIndex());
                lifeIndex.setMakeupIndex(data.getLifeIndex().getMakeupIndex());
            }

            if (existing != null) {
                // 更新现有记录
                lifeIndexMapper.updateById(lifeIndex);
            } else {
                // 插入新记录
                lifeIndexMapper.insert(lifeIndex);
            }

        } catch (Exception e) {
            System.out.println("生活指数解析失败: " + e.getMessage());
            throw new RuntimeException("生活指数解析失败: " + e.getMessage());
        }
    }


    /**
     * 处理24小时天气数据（存在则更新，不存在则插入）
     * @param cityWeatherId 城市天气ID
     * @param hourlyDataList API返回的小时数据列表
     */

    private void handleHourlyData(int cityWeatherId, List<HourData> hourlyDataList) {
        try {
            if (hourlyDataList == null || hourlyDataList.isEmpty()) {
                System.out.println("无24小时数据");
                return;
            }

            // 1. 删除该城市的所有24小时天气数据
            LambdaQueryWrapper<HourData> deleteWrapper = new LambdaQueryWrapper<>();
            deleteWrapper.eq(HourData::getCityWeatherId, cityWeatherId);
            int deletedCount = hour1Mapper.delete(deleteWrapper);

            // 2. 插入新数据
            for (HourData hourData : hourlyDataList) {
                // 设置关联ID
                hourData.setCityWeatherId(cityWeatherId);

                // 修正非法风向角度
                int windDegree = hourData.getWindDegree();
                hourData.setWindDegree(windDegree < 0 || windDegree > 360 ? 0 : windDegree);

                // 插入新记录
                hour1Mapper.insert(hourData);
                System.out.println("插入24小时数据: " + hourData.getHour());
            }

        } catch (Exception e) {
            System.out.println("24小时预报处理失败: " + e.getMessage());
            throw new RuntimeException("24小时预报处理失败: " + e.getMessage());
        }
    }


    /**
     * 异步更新所有城市天气数据
     */
    private void updateAllCitiesDataAsync(List<String> cityNames, int userId) {
        // 使用线程池异步处理
        ExecutorService executor = Executors.newFixedThreadPool(5); // 可配置为Bean
        cityNames.forEach(cityName ->
                executor.submit(() -> updateSingleCityData(cityName, userId))
        );
    }

    /**
     * 更新单个城市天气数据
     */

    @Async("asyncExecutor")
    protected void updateSingleCityData(String cityName, int userId) {
        try {
            // 复用现有的天气数据同步逻辑
            String host = "https://getweather.market.alicloudapi.com";
            String path = "/lundear/weather1d";
            String method = "GET";

            // 构造请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "APPCODE " + aliyunAppCode);

            // 构造查询参数
            Map<String, String> querys = new HashMap<>();
            querys.put("areaCn", cityName);
            querys.put("needObserve", "1");
            querys.put("needIndex", "1");

            // 调用API获取数据
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            if (response.getStatusLine().getStatusCode() != 200) {
                System.out.println("城市：" + cityName + " 数据更新失败");
                return;
            }

            // 解析数据
            String responseBody = EntityUtils.toString(response.getEntity());
            AliyunWeatherResponse aliyunResponse = JSON.parseObject(responseBody, AliyunWeatherResponse.class);
            DataInfo data = aliyunResponse.getData();
            Now now = data.getNow();

            // 查询是否已有数据
            LambdaQueryWrapper<CityWeather> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CityWeather::getUserId, userId)
                    .eq(CityWeather::getCityName, cityName);
            CityWeather cityWeather = weatherMapper.selectOne(wrapper);

            updateExistingWeather(cityWeather, now);


            // 更新关联数据
            JSONObject observe24h = JSON.parseObject(responseBody)
                    .getJSONObject("data")
                    .getJSONObject("observe24h");
            List<HourData> hourDataList = JSON.parseArray(observe24h.getString("od2"), HourData.class);
            handleHourlyData(cityWeather.getId(), hourDataList);
            handleLifeIndex(cityWeather.getId(), data);


            // 调用阿里云API获取天气数据

            path = "/lundear/weather7d";

            // 设置请求头
            headers.put("Authorization", "APPCODE " + aliyunAppCode);
            // 设置查询参数
            querys = new HashMap<>();
            querys.put("areaCn", cityName);
            querys.put("needObserve", "1");//是否需要24小时天气指数；1:需要，0:不需要
            querys.put("needIndex", "1");//是否需要生活指数数据；1:需要，0:不需要

            // 使用 HttpUtils 发起请求
            response = HttpUtils.doGet(host, path, method, headers, querys);

            int statusCode = response.getStatusLine().getStatusCode();
            responseBody = EntityUtils.toString(response.getEntity());;

            // 验证HTTP响应状态
            if (statusCode != 200) {
                System.out.println("获取用户所有城市天气失败");
            }

            aliyunResponse = JSON.parseObject(responseBody, AliyunWeatherResponse.class);

            //天气数据
            data = aliyunResponse.getData();
            System.out.println("天气数据：" + data);

            // 处理7天预报
            handleSevenDayForecast(cityWeather.getId(), data);


        } catch (Exception e) {
            System.out.println("城市：" + cityName + " 数据更新失败: " + e.getMessage());
        }
    }



    private void handleSevenDayForecast(int cityWeatherId, DataInfo data) {
        try {
            List<SevenDay> forecastList = List.of(data.getD1(), data.getD2(), data.getD3(),
                    data.getD4(), data.getD5(), data.getD6(), data.getD7());

            System.out.println("forecastList = " + forecastList);

            for (SevenDay day : forecastList) {
                if (day == null || day.getLocalDate() == null) continue;

                LambdaQueryWrapper<DailyForecast> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(DailyForecast::getCityWeatherId, cityWeatherId)
                        .eq(DailyForecast::getForecastDate, day.getLocalDate());

                DailyForecast existing = dailyForecastMapper.selectOne(wrapper);

                DailyForecast forecast;
                if (existing != null) {
                    forecast = existing;
                } else {
                    forecast = new DailyForecast();
                    forecast.setCityWeatherId(cityWeatherId);
                    forecast.setForecastDate(day.getLocalDate());
                }

                // 赋值字段
                forecast.setWeatherCondition(day.getWeather());
                forecast.setWeatherIcon(parseWeatherIcon(day.getWeather()));
                forecast.setMinTemperature(parseInt(day.getTemperatureMin()));
                forecast.setMaxTemperature(parseInt(day.getTemperatureMax()));

                // 插入或更新
                if (existing != null) {
                    dailyForecastMapper.updateById(forecast);
                    System.out.println("更新7天预报数据: " + day.getTime());
                } else {
                    dailyForecastMapper.insert(forecast);
                    System.out.println("插入新7天预报数据: " + day.getTime());
                }
            }

        } catch (Exception e) {
            System.out.println("7天预报处理失败: " + e.getMessage());
            throw new RuntimeException("7天预报处理失败: " + e.getMessage());
        }
    }

    private static final Map<String, String> WEATHER_ICON_MAP = new LinkedHashMap<>();

    static {
        WEATHER_ICON_MAP.put("雷阵雨", "thunderstorm");
        WEATHER_ICON_MAP.put("暴雨", "storm");
        WEATHER_ICON_MAP.put("大雪", "snow");
        WEATHER_ICON_MAP.put("中雪", "snow");
        WEATHER_ICON_MAP.put("小雪", "snow");
        WEATHER_ICON_MAP.put("大风", "windy");
        WEATHER_ICON_MAP.put("多云", "cloudy");
        WEATHER_ICON_MAP.put("晴", "sunny");
        WEATHER_ICON_MAP.put("阴", "overcast");
        WEATHER_ICON_MAP.put("雨", "rain");
        WEATHER_ICON_MAP.put("雪", "snow");
        WEATHER_ICON_MAP.put("雾", "fog");
        WEATHER_ICON_MAP.put("霾", "haze");
        WEATHER_ICON_MAP.put("冰雹", "hail");
        WEATHER_ICON_MAP.put("沙尘", "dust");
        WEATHER_ICON_MAP.put("雷", "thunderstorm");
        WEATHER_ICON_MAP.put("阵雨", "rain");
        WEATHER_ICON_MAP.put("中雨", "rain");
        WEATHER_ICON_MAP.put("小雨", "rain");
        WEATHER_ICON_MAP.put("雨夹雪", "rain_snow");
    }


    //转化天气图标
    private String parseWeatherIcon(String weather) {
        if (weather == null || weather.isEmpty()) {
            return "unknown";
        }

        // 如果包含“转”，优先匹配“转”后的天气
        if (weather.contains("转")) {
            String[] parts = weather.split("转");
            if (parts.length >= 2) {
                String secondPart = parts[1].trim();
                for (Map.Entry<String, String> entry : WEATHER_ICON_MAP.entrySet()) {
                    if (secondPart.contains(entry.getKey())) {
                        return entry.getValue();
                    }
                }
            }
        }

        // 否则匹配整个天气描述
        for (Map.Entry<String, String> entry : WEATHER_ICON_MAP.entrySet()) {
            if (weather.contains(entry.getKey())) {
                return entry.getValue();
            }
        }

        return "unknown"; // 默认图标
    }



    /**
     * 更新现有天气数据（NOW）
     * @param existing 需要更新的CityWeather对象
     * @param now      提供新数据的Now对象
     * @return 更新后的CityWeather对象
     */
    private CityWeather updateExistingWeather(CityWeather existing, Now now) {
        try {
            // 使用工具方法处理字符串空值
            existing.setCityName(getStringValueOrDefault(now.getCityname(), "未知"));
            existing.setWeatherCondition(getStringValueOrDefault(now.getWeather(), "未知"));
            existing.setPrecipitation(getStringValueOrDefault(now.getRain(), "未降雨"));

            // 保持温度转换逻辑
            existing.setCurrentTemperature(parseInt(now.getTemp()));
            existing.setPerceivedTemperature(parseInt(now.getTemp()) + 2);

            // 使用工具方法处理风向代码
            existing.setWindDirection(WindDirectionUtils.getChineseDirection(
                    getStringValueOrDefault(now.getWde(), "未知")));

            // 使用工具方法处理风速等级
            existing.setWindSpeedLevel(extractWindLevel(
                    getStringValueOrDefault(now.getWS(), "无风")));

            weatherMapper.updateById(existing);
        } catch (Exception e) {
            System.out.println("更新天气数据失败: " + e.getMessage());
            throw new RuntimeException("更新天气数据失败: " + e.getMessage());
        }

        return existing;
    }


    /**
     * 创建新的城市天气数据
     * @param userId 用户ID
     * @param now  提供新数据的Now对象
     * @return 新创建的CityWeather对象
     */

    private CityWeather createNewWeather(int userId, Now now) {
        CityWeather newWeather = new CityWeather();
        try {
            //处理字符串空值
            newWeather.setCityName(getStringValueOrDefault(now.getCityname(), "未知"));
            newWeather.setWeatherCondition(getStringValueOrDefault(now.getWeather(), "未知"));
            newWeather.setPrecipitation(getStringValueOrDefault(now.getRain(), "未降雨"));

            //温度转换
            newWeather.setCurrentTemperature(parseInt(now.getTemp()));
            newWeather.setPerceivedTemperature(parseInt(now.getTemp()) + 2);

            //处理风向
            newWeather.setWindDirection(WindDirectionUtils.getChineseDirection(
                    getStringValueOrDefault(now.getWde(), "未知")));

            //处理风速等级
            newWeather.setWindSpeedLevel(extractWindLevel(
                    getStringValueOrDefault(now.getWS(), "无风")));

            newWeather.setUserId(userId);
            weatherMapper.insert(newWeather);
        } catch (Exception e) {
            System.out.println("创建天气数据失败: " + e.getMessage());
            throw new RuntimeException("创建天气数据失败: " + e.getMessage());
        }

        return newWeather;
    }

    private String getStringValueOrDefault(String value, String defaultValue) {
        return (value != null && !value.isEmpty()) ? value : defaultValue;
    }

    // 工具方法：安全转换字符串为整数
    //支持浮点数转换
    private int parseInt(String value) {
        try {
            if (value == null || value.isEmpty()) return 0;

            //使用正则移除所有非数字和小数点的字符（包括 ℃、°C、空格等）
            String cleanedValue = value.replaceAll("[^\\d.]", "");

            if (cleanedValue.isEmpty()) return 0;

            return (int) Math.round(Double.parseDouble(cleanedValue)); // 四舍五入处理
        } catch (NumberFormatException e) {
            //System.out.println("数值转换失败: " + value + "，清理后: " + cleanedValue);
            return 0;
        }
    }


}
